package www.openteam.com.ui.qualityCntrl;


import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.R;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.IPQCBadReason;
import www.openteam.com.bean.IPQCCheckItem;
import www.openteam.com.bean.IPQCDispose;
import www.openteam.com.bean.IPQCMsg00;
import www.openteam.com.bean.IPQCMsg01;
import www.openteam.com.bean.IPQCProduce;
import www.openteam.com.contract.qualityCntrl.IPQC00Contract;
import www.openteam.com.presenter.business.QryCstChildInfoPresenter;
import www.openteam.com.presenter.qualityCntrl.IPQC00Presenter;
import www.openteam.com.tool.ToastUtil;

/**
 * A simple {@link Fragment} subclass.
 */
public class IPQC00Fragment extends mBaseFragment<IPQC00Presenter>
        implements IPQC00Contract.IPQC00View {


    @Bind(R.id.ipqc_Produceno)
    TextView ipqcProduceno;
    @Bind(R.id.ipqc_groupname)
    TextView ipqcGroupname;
    @Bind(R.id.ipqc_custid)
    TextView ipqcCustid;
    @Bind(R.id.ipqc_custName)
    TextView ipqcCustName;
    @Bind(R.id.ipqc_orderno)
    TextView ipqcOrderno;
    @Bind(R.id.ipqc_onumb)
    TextView ipqcOnumb;
    @Bind(R.id.ipqc_Prodcode)
    TextView ipqcProdcode;
    @Bind(R.id.ipqc_reqnumb)
    TextView ipqcReqnumb;
    @Bind(R.id.ipqc_Prodname)
    TextView ipqcProdname;
    @Bind(R.id.ipqc_PartID)
    TextView ipqcPartID;
    @Bind(R.id.ipqc_StartTime)
    TextView ipqcStartTime;
    @Bind(R.id.ipqc_EndTime)
    TextView ipqcEndTime;
    @Bind(R.id.ipqc_SampleTime)
    EditText ipqcSampleTime;
    @Bind(R.id.ipqc_SampleNo)
    EditText ipqcSampleNo;
    @Bind(R.id.ipqc_BadNo)
    EditText ipqcBadNo;
    @Bind(R.id.ipqc_JudgeResult)
    Spinner ipqcJudgeResult;
    @Bind(R.id.ipqc_ProcessMode)
    Spinner ipqcProcessMode;
    @Bind(R.id.ipqc_ReworkNo)
    EditText ipqcReworkNo;
    @Bind(R.id.ipqc_Complement)
    EditText ipqcComplement;
    @Bind(R.id.ipqc_ProductSche)
    Spinner ipqcProductSche;
    @Bind(R.id.ipqc_Note)
    EditText ipqcNote;
    @Bind(R.id.ipqc_childItem)
    LinearLayout mChildLinearLayout;
    @Bind(R.id.ipqc_NAddView)
    ImageButton addBtn;
    @Bind(R.id.ipqc_RemoveView)
    ImageButton removeBtn;
    @Bind(R.id.ipqc_save)
    Button btn_save;
    @Bind(R.id.ipqc_cancle)
    Button btn_cancle;
    @Bind(R.id.ipqc_audit)
    Button btn_audit;
    @Bind(R.id.ipqc_Unaudit)
    Button btn_unAudit;
    private String TAG = getClass().getSimpleName();
    private List<IPQCDispose.DataBeanX.DataBean> disposeData;
    private IPQCMsg00.DataBeanX.DataBean data00;
    private IPQCMsg01.DataBeanX.DataBean data01;
    private View mChildView;
    int markId = 0;
    private List<ViewHolder> viewHolderList;
    private List<View> viewList;
    private ArrayAdapter<String> checkItemAdapter;
    private ArrayAdapter<String> badReasonAdapter;
    private List<IPQCBadReason.DataBeanX.DataBean> badReasondata;
    private List<IPQCCheckItem.DataBeanX.DataBean> cheeckItemData;
    private ArrayList<String> proscheList;
    private ArrayList<String> judgeResultList;
    private ArrayList<String> progessModeList;

    public IPQC00Fragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_ipqc00, container, false);
        ButterKnife.bind(this, view);
        mPresenter = loadPresenter();
        initData();
        initView();
        initListener();
        return view;
    }

    @Override
    protected void initData() {
        if (mPresenter != null)
            mPresenter.attachView(this);

        //生产进度
        proscheList = new ArrayList<>();
        proscheList.add("暂停");
        proscheList.add("放行");
        ArrayAdapter<String> proscheAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, proscheList);
        proscheAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ipqcProductSche.setAdapter(proscheAdapter);

        //判定结果
        judgeResultList = new ArrayList<>();
        judgeResultList.add("补数");
        judgeResultList.add("返工");
        judgeResultList.add("作废");
        ArrayAdapter<String> judgeResultAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, judgeResultList);
        judgeResultAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ipqcJudgeResult.setAdapter(judgeResultAdapter);

        //处理方法
        progessModeList = new ArrayList<>();
        progessModeList.add("合格");
        progessModeList.add("不合格");
        progessModeList.add("待定");
        ArrayAdapter<String> progessModeAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, progessModeList);
        progessModeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ipqcProcessMode.setAdapter(progessModeAdapter);

        if (null != data00) {
            ipqcProduceno.setText(data00.getCode());
            ipqcGroupname.setText(data00.getGroupname());
            ipqcCustid.setText(data00.getCustid());
            ipqcCustName.setText(data00.getCustName());
            ipqcOrderno.setText(data00.getOrderno());
            ipqcOnumb.setText(data00.getOnumb());
            ipqcProdcode.setText(data00.getCode());
            ipqcProdname.setText(data00.getName());
            ipqcReqnumb.setText(data00.getReqnumb());
            ipqcPartID.setText(data00.getPartID());
        } else if (null != data01) {
            ipqcProduceno.setText(data01.getProduceno());
            ipqcGroupname.setText(data01.getGroupname());
            ipqcCustid.setText(data01.getCustcode());
            ipqcCustName.setText(data01.getCustname());
            ipqcOrderno.setText(data01.getRdsno());
            ipqcPartID.setText(data01.getPartId());
            ipqcOnumb.setText(data01.getAllcount() + "");
            ipqcProdcode.setText(data01.getProdcode());
            ipqcReqnumb.setText(data01.getFBackCount() + "");
            ipqcProdname.setText(data01.getProdname());
        }

        mPresenter.findCheckItem();
        mPresenter.findBadReason();
    }

    @Override
    protected void initListener() {
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                markId++;
                mChildView = View.inflate(getContext(), R.layout.ipqc_child_layout, null);
                mChildView.setId(markId);
                getViewInstance(mChildView);
                mChildLinearLayout.addView(mChildView);
            }
        });
        removeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int childNum = mChildLinearLayout.getChildCount();
                if (childNum > 1) {
                    mChildLinearLayout.removeViewAt(childNum - 1);
                    viewHolderList.remove(viewHolderList.size() - 1);
                    viewList.remove(viewList.size() - 1);
                    markId--;

                }
            }
        });
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btn_audit.setVisibility(View.VISIBLE);
                btn_unAudit.setVisibility(View.VISIBLE);
                ToastUtil.showToast(getContext(), "保存成功");
            }
        });
        btn_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ipqcSampleTime.setText("");
                ipqcBadNo.setText("");
                ipqcSampleNo.setText("");
                ipqcStartTime.setText("");
                ipqcEndTime.setText("");
                getFragmentManager().popBackStack();
            }
        });

        ipqcStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ipqcStartTime.setTag(ipqcStartTime);
                selectCalendar(ipqcStartTime);
            }
        });
        ipqcEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ipqcEndTime.setTag(ipqcEndTime);
                selectCalendar(ipqcEndTime);
            }
        });
        btn_audit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(getContext())
                        .setTitle("提示")
                        .setMessage("记录审核后不能进行修改和删除，是否确认审核")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                ipqcSampleTime.setEnabled(false);
                                ipqcBadNo.setEnabled(false);
                                ipqcSampleNo.setEnabled(false);
                                ipqcReworkNo.setEnabled(false);
                                ipqcComplement.setEnabled(false);
                                ipqcStartTime.setClickable(false);
                                ipqcEndTime.setClickable(false);
                                ipqcJudgeResult.setEnabled(false);
                                ipqcProcessMode.setEnabled(false);
                                ipqcProductSche.setEnabled(false);
                                addBtn.setClickable(false);
                                removeBtn.setClickable(false);
                            }
                        })
                        .setNegativeButton("否", null)
                        .show();
            }
        });

        btn_unAudit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(getContext())
                        .setTitle("提示")
                        .setMessage("是否进行反审核")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                ipqcSampleTime.setEnabled(true);
                                ipqcBadNo.setEnabled(true);
                                ipqcSampleNo.setEnabled(true);
                                ipqcReworkNo.setEnabled(true);
                                ipqcComplement.setEnabled(true);
                                ipqcStartTime.setClickable(true);
                                ipqcEndTime.setClickable(true);
                                ipqcJudgeResult.setEnabled(true);
                                ipqcProcessMode.setEnabled(true);
                                addBtn.setClickable(true);
                                removeBtn.setClickable(true);
                            }
                        })
                        .setNegativeButton("否", null)
                        .show();
            }
        });
    }

    @Override
    protected void initView() {
        viewHolderList = new ArrayList<>();
        viewList = new ArrayList<>();
//        mChildView = View.inflate(getContext(), R.layout.ipqc_child_layout, null);
//        mChildView.setId(markId);
//        getViewInstance(mChildView);
//        mChildLinearLayout.addView(mChildView);
        //首先隐藏审核和反审核按钮
        btn_audit.setVisibility(View.INVISIBLE);
        btn_unAudit.setVisibility(View.INVISIBLE);
    }

    private void getViewInstance(View mChildView) {
        ViewHolder vh = new ViewHolder();
        vh.id = mChildView.getId();
        vh.CcheckItem = (Spinner) mChildView.findViewById(R.id.ipqc_CheckItem);
        vh.CbadItem = (TextView) mChildView.findViewById(R.id.ipqc_BadItem);
        vh.Cnum = (EditText) mChildView.findViewById(R.id.ipqc_Num);
        vh.CbadReason = (Spinner) mChildView.findViewById(R.id.ipqc_BadReason);
        //设置数据
        vh.CcheckItem.setAdapter(checkItemAdapter);
        vh.CbadReason.setAdapter(badReasonAdapter);
        // 设置监听


        vh.CcheckItem.setOnItemSelectedListener(checkItemListener);

        viewHolderList.add(vh);
        viewList.add(mChildView);
    }

    AdapterView.OnItemSelectedListener checkItemListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            IPQCCheckItem.DataBeanX.DataBean dataBean = cheeckItemData.get(i);
            View v2 = (View) adapterView.getParent().getParent().getParent();
            for (int j = 0; j < mChildLinearLayout.getChildCount() - 1; j++) {
                ViewHolder viewHolder = viewHolderList.get(j);
                Log.e("createclass", "v2.getId()==" + v2.getId() + "  viewHolder.id==" + viewHolder.id);
                if (v2.getId() == viewHolder.id) {
                    viewHolder.CbadItem.setText(dataBean.getName());
                    viewHolder.CbadItem.setTag(dataBean.getCode());
                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    };

    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    protected IPQC00Presenter loadPresenter() {
        return new IPQC00Presenter();
    }

    /**
     * 从主页面传递过来的数据,
     *
     * @param dataBean
     */
    public void getdata00(IPQCMsg00.DataBeanX.DataBean dataBean) {
        data00 = dataBean;

    }

    public void getdata01(IPQCMsg01.DataBeanX.DataBean dataBean) {
        data01 = dataBean;

    }

    public void selectCalendar(final TextView v) {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                v.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    private void showExitDialog01(String tips){
        new AlertDialog.Builder(getContext())
                .setTitle("提示")
                .setMessage(tips)
                .setPositiveButton("是", null)
                .setNegativeButton("否", null)
                .show();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    /*
    检验项目
     */
    @Override
    public void findCheckItem(IPQCCheckItem ipqcCheckItem) {
        cheeckItemData = ipqcCheckItem.getData().getData();
        ArrayList<String> checkItemList = new ArrayList<>();
        for (IPQCCheckItem.DataBeanX.DataBean dataBean : cheeckItemData) {
            checkItemList.add(dataBean.getItemname());
        }
        checkItemAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, checkItemList);
        checkItemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mChildView = View.inflate(getContext(), R.layout.ipqc_child_layout, null);
        mChildView.setId(markId);
        getViewInstance(mChildView);
        mChildLinearLayout.addView(mChildView);
    }

    /*
    不良原因
     */
    @Override
    public void findBadReason(IPQCBadReason ipqcBadReason) {
        badReasondata = ipqcBadReason.getData().getData();
        ArrayList<String> badReasonList = new ArrayList<>();
        for (IPQCBadReason.DataBeanX.DataBean dataBean : badReasondata) {
            badReasonList.add(dataBean.getName());
        }
        badReasonAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, badReasonList);
        badReasonAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    }

    /*
    判定结果
     */
    @Override
    public void findDispose(IPQCDispose ipqcDispose) {
        disposeData = ipqcDispose.getData().getData();
        ArrayList<String> disposeList = new ArrayList<>();
        for (IPQCDispose.DataBeanX.DataBean dataBean : disposeData) {
            disposeList.add(dataBean.getName());
        }
        ArrayAdapter<String> disposeAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, disposeList);
        disposeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ipqcJudgeResult.setAdapter(disposeAdapter);
    }

    @Override
    public void fail(String msg) {
        Log.e(TAG, "fail: " + msg);
    }

    @Override
    public void onRefresh() {

    }

    public class ViewHolder {
        private int id = -1;
        private Spinner CcheckItem;
        private EditText Cnum;
        private TextView CbadItem;
        private Spinner CbadReason;
    }
}
